using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WLYT.Application.Interfaces;
using WLYT.Domain.Model;
using WLYT.Repository;

namespace WLYT.Application.Services
{	
    public class RoleService : BaseService<Role>, IRoleService
    {
        public ISqlSugarRepository<Role> RoleRepository;
        public ISqlSugarRepository<User> UserRepository;
        public RoleService(ISqlSugarRepository<Role> roleRepository, ISqlSugarRepository<User> userRepository) : base(roleRepository)
        {
            RoleRepository = roleRepository;
            UserRepository = userRepository;
        }

        public async Task<bool> Remove(int id)
        {
            if (await UserRepository.IsAnyAsync(p => p.RoleId == id))
            {
                return false;
            }
            return await RoleRepository.DeleteByIdAsync(id);
        }

        public async Task<Tuple<IList<Role>, int>> GetModelsByPageAsync(string search, int pageSize, int pageIndex)
        {
            var result = await GetPageListAsync(p => p.Name.Contains(search ?? ""), pageSize, pageIndex, p => p.Id);
            return result;
        }

        public async Task<bool> Save(Role model)
        {
            var query = await GetByIdAsync(model.Id);
            if (query == null)
            {
                model.CreateTime = DateTime.Now;
                return await AddAsync(model);
            }
            else
            {
                query.Name = model.Name;
                query.Permission = model.Permission;
                query.UpdateTime = DateTime.Now;
                return await UpdateAsync(query);
            }
        }

        public async Task<List<Role>> GetAll()
        {
            return await RoleRepository.GetListAsync();
        }
    }
}